package com.settlement.system.rules;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.settlement.system.model.entity.SysAudit;
import com.settlement.system.model.entity.SysAuditRule;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

/**
 * 2a-1、超期未退款规则器
 */
public class OverdueNoRefundRuler implements CommonRuler {
    @Override
    public boolean check(SysAudit sysAudit, SysAuditRule auditRule) {
        // "当前日期T-业务日期≥180天（可配置）
        //且应收账款余额＜-50（可配置）
        //且收款金额＞0
        //且收款金额+退款金额+保证金退款金额＞0
        //且退款金额+保证金退款金额=0
        //且发货金额＞0
        //且退货金额＜0"
        // 第一个条件
        LocalDateTime now = LocalDateTime.now();
        long days = Math.abs(Duration.between(sysAudit.getBusinessDate(), now).toDays());
        String expression = "a>=" + auditRule.getDateConfig();
        Expression compiledExp = AviatorEvaluator.compile(expression);
        Map<String, Object> env = new HashMap<>();
        env.put("a", days);
        boolean daysBool = (Boolean) compiledExp.execute(env);
        expression = "a<" + auditRule.getReceiveCount();
        compiledExp = AviatorEvaluator.compile(expression);
        env = new HashMap<>();
        env.put("a", sysAudit.getReceiveBillAmount());
        boolean billBool = (Boolean) compiledExp.execute(env);
        return daysBool && billBool &&
                sysAudit.getReceiveAmount().compareTo(BigDecimal.ZERO) > 0 &&
                sysAudit.getReceiveAmount().add(sysAudit.getRefundAmount()).add(sysAudit.getDepositAmount()).compareTo(BigDecimal.ZERO) > 0 &&
                sysAudit.getRefundAmount().add(sysAudit.getDepositAmount()).compareTo(BigDecimal.ZERO) == 0 &&
                sysAudit.getSendAmount().compareTo(BigDecimal.ZERO) > 0 &&
                sysAudit.getReturnAmount().compareTo(BigDecimal.ZERO) < 0;
    }
}
